package com.syspeak.modules.spring.http.converter.json;

import java.io.IOException;

import org.apache.struts2.json.JSONException;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;

import com.syspeak.modules.spring.web.json.JsonConfigedObject;
import com.syspeak.modules.spring.web.servlet.mvc.annotation.JsonConfig;
import com.syspeak.modules.utils.json.JsonLibObjectMapper;

/**
 * 基于JSON-LIB的HttpMessageConverter
 * @company SysPeak (C) Copyright
 * @category MappingJsonLibHttpMessageConverter
 * @version 1.0
 * @since 2011-10-25
 * @author JemiZhuu(周士淳)
 */
public class MappingJsonLibHttpMessageConverter extends MappingJacksonHttpMessageConverter {

	private JsonLibObjectMapper objectMapper = new JsonLibObjectMapper();

	@Override
	protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException,
			HttpMessageNotWritableException {
		String excludeProperties = "";
		String includeProperties = "";
		boolean excludeNullProperties = false;
		if (JsonConfigedObject.class.isAssignableFrom(o.getClass())) {
			JsonConfig jsonConfig = ((JsonConfigedObject) o).getJsonConfig();
			excludeProperties = jsonConfig.excludeProperties();
			includeProperties = jsonConfig.includeProperties();
			excludeNullProperties = jsonConfig.excludeNullProperties();
		}
		try {
			objectMapper.serialize(outputMessage.getBody(), o, excludeProperties, includeProperties,
					excludeNullProperties);
		} catch (JSONException e) {
			e.printStackTrace();
			throw new HttpMessageNotWritableException(e.getMessage(), e.getCause());
		}
	}
}